<?php
/*
* 2007-2012 PrestaShop 
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <contact@prestashop.com>
*  @copyright  2007-2012 PrestaShop SA
*  @version  Release: $Revision: 8783 $
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

if (!defined('_PS_VERSION_'))
	exit;

class BlockBestRated extends Module
{
    public function __construct()
    {
        $this->name = 'blockbestrated';
        $this->tab = 'front_office_features';
        $this->version = '1.5';
		$this->author = 'Zenith';
		$this->need_instance = 0;

        parent::__construct();

        $this->displayName = $this->l('Best rated products block');
        $this->description = $this->l('Displays a block featuring the best rated products');
    }

    public function install()
    {
        if (!parent::install() OR !$this->registerHook('rightColumn') OR !$this->registerHook('header'))
			return false;

		Configuration::updateValue('PS_BLOCK_BESTRATED_NBR', 5);
		Configuration::updateValue('PS_BLOCK_BESTRATED_DISPLAY', 1);
		Configuration::updateValue('PS_BLOCK_BESTRATED_MIN_VOTES', 2);
		Configuration::updateValue('PS_BLOCK_BESTRATED_CAT_ONLY', 1);
		Configuration::updateValue('PS_BLOCK_BESTRATED_ATO', 0);
		return true;
    }

	public function uninstall()
    {
		Configuration::deleteByName('PS_BLOCK_BESTRATED_NBR');
		Configuration::deleteByName('PS_BLOCK_BESTRATED_DISPLAY');
		Configuration::deleteByName('PS_BLOCK_BESTRATED_MIN_VOTES');
		Configuration::deleteByName('PS_BLOCK_BESTRATED_CAT_ONLY');
		Configuration::deleteByName('PS_BLOCK_BESTRATED_ATO');
		return parent::uninstall();
    } 

	public function getContent()
	{
		$output = '<h2>'.$this->displayName.'</h2>';
		if (Tools::isSubmit('submitBlockBestRated'))
		{
			if (!$minVotes = Tools::getValue('minVotes') OR empty($minVotes))
				$output .= '<div class="alert error">'.$this->l('You should fill the "minimum votes" field').'</div>';
			else
			    Configuration::updateValue('PS_BLOCK_BESTRATED_MIN_VOTES', (int)($minVotes));

			if (!$productNbr = Tools::getValue('productNbr') OR empty($productNbr))
				$output .= '<div class="alert error">'.$this->l('Please fill in the "products displayed" field.').'</div>';
			elseif ((int)($productNbr) == 0)
				$output .= '<div class="alert error">'.$this->l('Invalid number.').'</div>';
			else
			{
				Configuration::updateValue('PS_BLOCK_BESTRATED_NBR', (int)($productNbr));
			    Configuration::updateValue('PS_BLOCK_BESTRATED_DISPLAY', (int)(Tools::getValue('always_display')));
			    Configuration::updateValue('PS_BLOCK_BESTRATED_CAT_ONLY', (int)(Tools::getValue('cat_only')));
			    Configuration::updateValue('PS_BLOCK_BESTRATED_ATO', (int)(Tools::getValue('display_ato')));
			    $output .= '<div class="conf confirm"><img src="../img/admin/ok.gif" alt="'.$this->l('Confirmation').'" />'.$this->l('Settings updated').'</div>';
			}
		}
		return $output.$this->displayForm();
	}

	public function displayForm()
	{
		$output = '
		<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post">
			<fieldset><legend><img src="'.$this->_path.'logo.gif" alt="" title="" />'.$this->l('Settings').'</legend>
				<label>'.$this->l('Products displayed').'</label>
				<div class="margin-form">
					<input size="5" type="text" name="productNbr" value="'.(int)(Configuration::get('PS_BLOCK_BESTRATED_NBR')).'" />
					<p class="clear">'.$this->l('Set the number of products to be displayed in this block').'</p>
				</div>
				<label>'.$this->l('Always display block').'</label>
				<div class="margin-form">
					<input type="radio" name="always_display" id="display_on" value="1" '.(Tools::getValue('always_display', Configuration::get('PS_BLOCK_BESTRATED_DISPLAY')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="display_on"> <img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="always_display" id="display_off" value="0" '.(!Tools::getValue('always_display', Configuration::get('PS_BLOCK_BESTRATED_DISPLAY')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="display_off"> <img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
					<p class="clear">'.$this->l('Show the block even if no products have been rated.').'</p>
				</div>
				<label>'.$this->l('Minimum votes').'</label>
				<div class="margin-form">
					<input size="5" type="text" name="minVotes" value="'.(int)(Configuration::get('PS_BLOCK_BESTRATED_MIN_VOTES')).'" />
					<p class="clear">'.$this->l('Set the number of votes required for a product to be displayed in this block.').'</p>
				</div>
				<label>'.$this->l('Show only "available to order" products').'</label>
				<div class="margin-form">
					<input type="radio" name="display_ato" id="ato_on" value="1" '.(Tools::getValue('display_ato', Configuration::get('PS_BLOCK_BESTRATED_ATO')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="display_ato_on"> <img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="display_ato" id="ato_off" value="0" '.(!Tools::getValue('display_ato', Configuration::get('PS_BLOCK_BESTRATED_ATO')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="display_ato_off"> <img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
					<p class="clear">'.$this->l('Show rated products that are "available to order" only.').'</p>
				</div>
				<label>'.$this->l('Show category specific products').'</label>
				<div class="margin-form">
					<input type="radio" name="cat_only" id="cat_only_on" value="1" '.(Tools::getValue('cat_only', Configuration::get('PS_BLOCK_BESTRATED_CAT_ONLY')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="cat_only_on"> <img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="cat_only" id="cat_only_off" value="0" '.(!Tools::getValue('cat_only', Configuration::get('PS_BLOCK_BESTRATED_CAT_ONLY')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="cat_only_off"> <img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
					<p class="clear">'.$this->l('Show products only from the category when viewing category page.').'</p>
				</div>
				<center><input type="submit" name="submitBlockBestRated" value="'.$this->l('Save').'" class="button" /></center>
			</fieldset>
		</form>';
		return $output;
	}

	public function getBestRated($id_lang, $nbProducts = 10, $id_category, $id_product)
	{
		global $link, $cookie;
	
		if ($nbProducts < 1) 
			$nbProducts = 10;

		if ($id_product && empty($id_category))
			$id_category = Db::getInstance()->getValue('SELECT `id_category_default` FROM `'._DB_PREFIX_.'product` WHERE `id_product` = '.$id_product);

		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT p.`id_product`, pl.`link_rewrite`, pl.`name`, i.`id_image`, il.`legend`, p.`ean13`, cl.`link_rewrite` AS category, ROUND((r.total_value / r.total_votes), 1) as rating
		FROM `'._DB_PREFIX_.'product` p
		LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)($id_lang).')
		LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)($id_lang).')
	    LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (cl.`id_category` = p.`id_category_default` AND cl.`id_lang` = '.(int)($id_lang).')
		LEFT JOIN `'._DB_PREFIX_.'ratings` r ON (r.`id` = p.`id_product`)
		WHERE p.`active` = 1
		'.((Configuration::get('PS_BLOCK_BESTRATED_ATO')) ? ' AND p.`available_to_order` = 1' : '').'
		'.(($id_category && Configuration::get('PS_BLOCK_BESTRATED_CAT_ONLY')) ? ' AND p.`id_category_default` = '.$id_category : '').'
		AND r.`total_votes` >= '.Configuration::get('PS_BLOCK_BESTRATED_MIN_VOTES').'
		AND p.`id_product` IN (
			SELECT cp.`id_product`
			FROM `'._DB_PREFIX_.'category_group` cg
			LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`)
			WHERE cg.`id_group` '.(!$cookie->id_customer ?  '= 1' : 'IN (SELECT id_group FROM '._DB_PREFIX_.'customer_group WHERE id_customer = '.(int)($cookie->id_customer).')').'
		)
		GROUP BY p.`id_product`
		ORDER BY `rating` DESC
		LIMIT '.(int)(0 * $nbProducts).', '.(int)($nbProducts));
		if (!$result)
			return $result;
		
		foreach ($result AS &$row)
		{
		 	$row['link'] = $link->getProductLink($row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']);
		 	$row['id_image'] = Product::defineProductImage($row, $id_lang);
		}
		return $result;
	}

    public function hookRightColumn($params)
    {
		if (Configuration::get('PS_CATALOG_MODE'))
			return;

		global $smarty;

		if ((int)(Tools::getValue('id_product')))
			$bestrateds = self::getBestRated((int)($params['cookie']->id_lang), (int)(Configuration::get('PS_BLOCK_BESTRATED_NBR')), 0, (int)(Tools::getValue('id_product')));
		else
			$bestrateds = self::getBestRated((int)($params['cookie']->id_lang), (int)(Configuration::get('PS_BLOCK_BESTRATED_NBR')), (int)(Tools::getValue('id_category')), 0);
		if (!$bestrateds AND !Configuration::get('PS_BLOCK_BESTRATED_DISPLAY'))
			return;
 		$best_rateds = array();
		if($bestrateds)
		foreach ($bestrateds AS $bestrated)
			$best_rateds[] = $bestrated;
                $smarty->assign(array('best_rateds' => $best_rateds, 'mediumSize' => Image::getSize('medium')));		
		
		return $this->display(__FILE__, 'blockbestrated.tpl');
	}
	
    public function hookLeftColumn($params)
	{
		return $this->hookRightColumn($params);
	}
	
    public function hookHeader($params)
	{
		if (Configuration::get('PS_CATALOG_MODE'))
			return;
		Tools::addCSS(($this->_path).'blockbestrated.css', 'all');
	}

}

